import { Component, Game, _decorator, director, game, Node, SceneAsset } from 'cc';
import { LoadingManager } from './LoadingManager';
import { LoadingBundle } from '../Config/BaseEnum';
import { TimeControler as TimeControler } from '../Control/TimeControler';
const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {
  static Singleton: GameManager;

  @property(Node)
  mainCamera: Node = null;

  static TimeControl: TimeControler = null!;

  constructor() {
    super();
    GameManager.Singleton = this;
  }

  protected start(): void {
    director.addPersistRootNode(this.node);
    game.on(Game.EVENT_SHOW, this.gameShow, this);
    game.on(Game.EVENT_HIDE, this.gameHide, this);
  }

  init() {
    GameManager.TimeControl = this.node.getComponent(TimeControler)!;
  }

  async runScene(scene: string) {
    const bundle = LoadingManager.Ins().getBundle(LoadingBundle.SceneBundle);
    const sceneAsset: SceneAsset = await new Promise<SceneAsset>((resolve, reject) => {
      bundle.loadScene(scene, (err, asset) => {
        if (err) {
          reject(err);
        } else {
          resolve(asset);
        }
      });
    });
    this.mainCamera = sceneAsset.scene.getChildByName('Main Camera');
    sceneAsset.scene.addChild(this.node);
    director.runScene(sceneAsset.scene);
  }

  /** 游戏切回前台 */
  gameShow() {
    console.log('游戏进入前台');
    // this.playMusic(SoundCode.BGM);
  }

  /** 游戏进入后台 */
  gameHide() {}
}
